package com.webside.points.wechat;


import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.webside.points.model.ExpertEntity;
import com.webside.points.model.IssueEntity;
import com.webside.points.model.UserEntity;
import com.webside.points.service.ExpertService;
import com.webside.points.service.IssueService;
import com.webside.points.service.UserService;
import com.webside.points.service.impl.ExpertServiceImpl;
import com.webside.points.service.impl.IssueServiceImpl;
import com.webside.points.service.impl.UserServiceImpl;



/**
 * 支付结果通知回调处理类
 * 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
 * @author apple
 *
 */
public class RewardResultNotify extends Notify {

	
	public RewardResultNotify(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
	}

	@Override
	public void ProcessNotify() throws NoSuchAlgorithmException,
			WxPayException, IOException, ParserConfigurationException,
			SAXException {
		WxPayData notifyData = GetNotifyData();
		
		// 检查支付结果中transaction_id是否存在
		if (!notifyData.IsSet("transaction_id")) {
			// 若transaction_id不存在，则立即返回结果给微信支付后台
			WxPayData res = new WxPayData();
			res.SetValue("return_code", "FAIL");
			res.SetValue("return_msg", "支付结果中微信订单号不存在");
			PrintWriter print = response.getWriter();
			print.write(res.ToXml());
			print.flush();
			print.close();
		}

		String transaction_id = notifyData.GetValue("transaction_id")
				.toString();

		// 查询订单，判断订单真实性
		if (!QueryOrder(transaction_id)) {
			// 若订单查询失败，则立即返回结果给微信支付后台
			WxPayData res = new WxPayData();
			res.SetValue("return_code", "FAIL");
			res.SetValue("return_msg", "订单查询失败");
			PrintWriter print = response.getWriter();
			print.write(res.ToXml());
			print.flush();
			print.close();
		}else {
			// 查询订单成功
			//更新用户的金额
			
			//修改付款金额
			String total_fee = (String) notifyData.GetValue("total_fee");
			//付款用户openId
			String openid = (String) notifyData.GetValue("openid");
			//附加数据（专家ID、问题ID）
			String attach = (String) notifyData.GetValue("attach");
			
			ExpertService expertService = ExpertServiceImpl.getInstance();
			ExpertEntity transaction = expertService.findByTransactionId(transaction_id);
			System.out.println("transaction：>>>"+transaction);
			//检验是否支付
			if(transaction==null){
				
				String array[]=attach.split(";");
				//更新交易订单
				ExpertEntity updateExpertEntity = new ExpertEntity();
				updateExpertEntity.setId(Integer.valueOf(array[0]));
				updateExpertEntity.setTransactionId(transaction_id);
				expertService.updateTransactionId(updateExpertEntity);
				//更新用户付款金额
				UserService userService=UserServiceImpl.getInstance();
				UserEntity user = userService.findByOpenId(openid);
				UserEntity userEntity=new UserEntity();
				double amount=user.getPayment();
				amount=amount+Util.centTurnAmount(total_fee);
				userEntity.setPayment(amount);
				userEntity.setOpenId(openid);
				userService.updatePayment(userEntity);
				
				//付款给专家
				
				System.out.println("附加值：>>>"+array[0]+"   "+array[1]+" transaction_id:>>>  "+transaction_id);
				UserEntity entity = userService.findExpertId(Integer.valueOf(array[0]));
				System.out.println("amount:>>>"+total_fee+"    "+Util.centTurnAmount(total_fee));
				//暂时不用
				//Wechat.transfersPay(entity.getOpenId(), total_fee, request);
				
				
				//更新专家收入金额
				
				ExpertEntity expertEntity=expertService.findById(entity.getExpertId());
				double rewardAmount=expertEntity.getRewardAmount();
				//扣除手续分
				DecimalFormat df =new DecimalFormat("0.00");  
				String s=df.format(Util.centTurnAmount(total_fee)-(Util.centTurnAmount(total_fee)*0.01));
				System.out.println("扣除手续分金额："+s);
				rewardAmount=rewardAmount+Double.valueOf(s);
				expertEntity.setRewardAmount(rewardAmount);
				System.out.println("修改专家金额："+expertEntity);
				expertService.updateAmount(expertEntity);		
				System.out.println("array[1]>>>:"+array[1]);
				//如果在问题内容中打赏修改打赏次数
				if(array[1]!=null){
					IssueService issueService = IssueServiceImpl.getInstance();
					IssueEntity issueEntity = issueService.findById(Integer.valueOf(array[1]));
					issueEntity.setRewardNumber(issueEntity.getRewardNumber()+1);
					issueEntity.setBrowseNumber(0);
					issueEntity.setStatus(null);
					issueService.updateStatus(issueEntity);
				}
				
			}
			
			
			
			//通知微信平台
			WxPayData res = new WxPayData();
			res.SetValue("return_code", "SUCCESS");
			res.SetValue("return_msg", "OK");
			PrintWriter print = response.getWriter();
			print.write(res.ToXml());
			print.flush();
			print.close();
			
		}
	}

	// 查询订单
	private boolean QueryOrder(String transaction_id)
			throws NoSuchAlgorithmException, WxPayException,
			ParserConfigurationException, SAXException, IOException {
		WxPayData req = new WxPayData();
		req.SetValue("transaction_id", transaction_id);
		WxPayData res = WxPayApi.OrderQuery(req, 0);
		if (res.GetValue("return_code").toString().equalsIgnoreCase("SUCCESS")
				&& res.GetValue("result_code").toString()
						.equalsIgnoreCase("SUCCESS")) {
			return true;
		} else {
			return false;
		}
	}

}
